/**
 * @Title: CmsHomeController.java
 * @Package com.alex.cms.web.controllers
 * @Description: (描述该文件做什么)
 * @author Alex Lu
 * @date 2019年9月11日 下午3:30:54
 * @version V1.0
 */
package com.alex.cms.web.controllers;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alex.cms.domain.CmsArticle;
import com.alex.cms.domain.CmsCategory;
import com.alex.cms.domain.CmsChannel;
import com.alex.cms.domain.CmsComment;
import com.alex.cms.domain.CmsSlide;
import com.alex.cms.domain.CmsSpecial;
import com.alex.cms.domain.CmsUser;
import com.alex.cms.service.ICmsArticleService;
import com.alex.cms.service.ICmsCategoryService;
import com.alex.cms.service.ICmsChannelService;
import com.alex.cms.service.ICmsCommentService;
import com.alex.cms.service.ICmsSlideService;
import com.alex.cms.service.ICmsSpecialService;
import com.alex.cms.service.ICmsUserService;
import com.alex.cms.web.constants.CMSConstants;
import com.alex.cms.web.form.UserForm;
import com.alex.cms.web.vo.ArticleVo;
import com.alex.cms.web.vo.ResultVo;
import com.alex.cms.web.vo.SpecialArticlesVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * @ClassName: CmsHomeController
 * @Description: cms系统主页
 * @author Alex Lu
 * @date 2019年9月11日 下午3:30:54
 *
 */
@Controller
public class CmsHomeController {
	@Autowired
	private ICmsChannelService channelService;

	@Autowired
	private ICmsCategoryService categoryService;

	@Autowired
	private ICmsArticleService articleService;

	@Autowired
	private ICmsSlideService slideService;

	@Autowired
	private ICmsUserService userService;

	@Autowired
	private ICmsCommentService commentService;
	
	@Autowired
	private ICmsSpecialService specialService;

	/**
	 * 
	 * @Title: showHomePage
	 * @Description: 展示主页的页面信息
	 * @return
	 * @return ModelAndView
	 */
	@RequestMapping("/")
	public ModelAndView showHomePage(@RequestParam(required = false, value = "channel") Integer channelId, @RequestParam(required = false, value = "category") Integer cateId,
			@RequestParam(required = false, value = "pageNo") Integer pageNo,
			HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();
		HttpSession session = request.getSession(false);
		if(session== null){
			UserForm userForm = new UserForm();
			mav.addObject("userForm",userForm);
			mav.setViewName("/passport/login");
			return mav;
		}
		mav = new ModelAndView("home");

		// 0. 获取已上热门文章

		IPage<ArticleVo> hotArticles = articleService.selectAllArticlesByUserId(new Page<ArticleVo>(1, 10), new QueryWrapper<ArticleVo>().eq("cms_article.hot", 1));
		// 假如是投票文章，就标题加[投票]
		for (ArticleVo vo : hotArticles.getRecords()) {
			if (vo.getType() == 1) {
				vo.setTitle("[投票]" + vo.getTitle());
			}
		}
		mav.addObject("hotArticles", hotArticles.getRecords());

		// 1. 获取所有列表和分类信息

		// 装载所有频道及其相关分类 的列表。频道和其分类使用Map进行映射
		List<Map<CmsChannel, List<CmsCategory>>> channelsAndCategories = new ArrayList<Map<CmsChannel, List<CmsCategory>>>();

		// 查询出所有频道信息
		List<CmsChannel> channels = channelService.list(new QueryWrapper<CmsChannel>().orderByAsc("sorted"));

		// 遍历频道列表，查询每个频道所对应的分类信息。并将绑定在一个Map中，然后再将Map添加到channelsAndCategories列表中
		for (CmsChannel channel : channels) {
			QueryWrapper<CmsCategory> queryWrapper = new QueryWrapper<CmsCategory>();
			queryWrapper.eq("channel_id", channel.getId()).orderByAsc("sorted");
			List<CmsCategory> categories = categoryService.list(queryWrapper);

			Map<CmsChannel, List<CmsCategory>> temp = new HashMap<CmsChannel, List<CmsCategory>>();

			temp.put(channel, categories);

			channelsAndCategories.add(temp);
		}

		mav.addObject(CMSConstants.CHANNESL_AND_CATEGORIES, channelsAndCategories);

		// 2. 如果传入频道id参数，则表明根据当前id查询相应频道信息，及分类信息
		if (channelId != null) {

			CmsChannel channel = null;
			CmsCategory category = null;

			// 遍历所有频道信息
			for (CmsChannel temp : channels) {
				if (channelId == temp.getId()) {

					// 获得当前 选择的频道信息
					channel = temp;

					// 遍历当前频道所有分类信息
					for (Map<CmsChannel, List<CmsCategory>> map : channelsAndCategories) {
						if (map.containsKey(channel)) {
							List<CmsCategory> cates = map.get(channel);

							// 获得当前频道的分类信息
							if (cateId != null) {
								for (CmsCategory cate : cates) {
									if (cate.getId() == cateId) {
										category = cate;
									}
								}
							} else {
								category = cates.get(0);
							}
						}
					}
				}
			}

			mav.addObject("channel", channel);
			mav.addObject("category", category.getId());

		}else{
			mav.addObject("channel", channels.get(0));
		}

		// 3. 如果分类id参数传入，则表明需要根据该 id查询相应的文章信息
		if (cateId != null) {
			pageNo = pageNo != null ?pageNo:1;
			IPage<ArticleVo> articles = articleService.selectAllArticlesByUserId(new Page<ArticleVo>(pageNo, 1), new QueryWrapper<ArticleVo>().eq("categroy_id", cateId));

			mav.addObject("articles", articles.getRecords());
			mav.addObject("currentPage",articles.getCurrent());
			mav.addObject("pages",articles.getPages());
		}else{
			mav.addObject("currentPage",1);
			mav.addObject("pages",1);
		}

		// 4. 获取最新文章内容
		IPage<ArticleVo> lastArticles = articleService.selectAllArticlesByUserId(new Page<ArticleVo>(1, 10), new QueryWrapper<ArticleVo>().eq("type", 0).orderByDesc("updated"));

		mav.addObject("lastArticles", lastArticles.getRecords());
		IPage<ArticleVo> lastVotes = articleService.selectAllArticlesByUserId(new Page<ArticleVo>(1, 10), new QueryWrapper<ArticleVo>().eq("type", 1).orderByDesc("updated"));

		mav.addObject("lastVotes", lastVotes.getRecords());
		//5.广告轮播
		List<CmsSlide> slides = slideService.list();
		mav.addObject("slides",slides);
		
		//专题
		IPage<CmsSpecial> specials = specialService.page(new Page<CmsSpecial>(1,5));
		List<SpecialArticlesVo> list = new ArrayList<SpecialArticlesVo>();
		for(CmsSpecial cmsSpecial:specials.getRecords()){
			SpecialArticlesVo specialArticlesVo = new SpecialArticlesVo();
			BeanUtils.copyProperties(cmsSpecial, specialArticlesVo);
			List<CmsArticle> cmsArticles = specialService.getArticleByAid(new QueryWrapper<CmsArticle>().eq("csa.sid ", cmsSpecial.getId()));
			specialArticlesVo.setArticles(cmsArticles);
			list.add(specialArticlesVo);
		}
		mav.addObject("specials",list);
		return mav;
	}
	
	@RequestMapping("/articlePage")
	public ModelAndView getNextArticle(@RequestParam("articleId")Integer articleId,
			@RequestParam("pageNo")Integer pageNo){
		CmsArticle article = articleService.getById(articleId);
		ModelAndView mav= new ModelAndView("redirect:/?channel="+article.getChannelId()+"&category="+article.getCategroyId()+"&pageNo="+pageNo);
				return mav;
		
	}

	/**
	 * 
	* @Title: comment
	* @Description: 用户发表评论
	* @param articleId
	* @param content
	* @param session
	* @return
	* @return ReusltVo
	 */
	@RequestMapping("/my/comment/{articleId}")
	@ResponseBody
	public ResultVo comment(@PathVariable("articleId") Integer articleId, @RequestParam("content") String content, HttpSession session) {
		CmsUser user = (CmsUser) session.getAttribute(CMSConstants.LOGIN_USER);
		ResultVo result = new ResultVo();
		CmsComment comment = new CmsComment();
		comment.setArticleId(articleId);
		comment.setUserId(user.getId());
		comment.setContent(content);
		comment.setCreated(new Date());
		boolean ret = commentService.save(comment);
		//评论数递增，必须先查询数据，然后在它原来的评论数上+1
		CmsArticle cmsArticle = articleService.getById(articleId);
		cmsArticle.setComments(cmsArticle.getComments()+1);
		articleService.updateById(cmsArticle);
		result.setStatus(ret == true ? CMSConstants.RESULT_STATUS_SUCCESS : CMSConstants.RESULT_STATUS_ERROR);
		result.setMessage(ret == true ? CMSConstants.RESULT_COMMENT_MESSAGE_SUCCESS : CMSConstants.RESULT_COMMENT_MESSAGE_ERROR);
		return result;
	}

}
